package top.jacktgq.cas;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * @Author CandyWall
 * @Date 2022/3/14--6:56
 * @Description
 */
public class AtomicIntegerDemo {
    public static void main(String[] args) {
        AtomicInteger i = new AtomicInteger();
        System.out.println(i.incrementAndGet()); // ++i
        System.out.println(i.getAndIncrement()); // i++
        System.out.println(i.addAndGet(5)); // i += 5; return i;
        System.out.println(i.getAndAdd(5)); // return i; i += 5;

        System.out.println(i.updateAndGet(value -> value * 10));

        while (true) {
            int prev = i.get();
            int next = prev * 5;
            if (i.compareAndSet(prev, next)) {
                break;
            }
        }
        System.out.println(i.get());


        // 模仿AtomicInteger内部的updateAndGet()方法自己做一个类似实现
        System.out.println(updateAndGet(i, x -> x / 4));
    }

    private static int updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
        int next;
        while (true) {
            int prev = i.get();
            next = operator.applyAsInt(prev);
            if (i.compareAndSet(prev, next)) {
                break;
            }
        }
        return next;
    }
}
